import { baseURL }  from './api-config.js'

// H5版本
// #ifdef H5
import Fly from 'flyio/dist/npm/fly'
// #endif

//微信小程序和APP版本
// #ifndef H5
import Fly from 'flyio/dist/npm/wx'
// #endif

const request = new Fly();

request.interceptors.request.use((request) => {

  request.baseURL = baseURL;
  
  const token = uni.getStorageSync('access_token');
  if (token) {
    //给所有请求添加自定义header
    request.headers["Authorization"] = token;
  }
  // 防止缓存
  if (request.method === 'POST' && request.headers['Content-Type'] !== 'multipart/form-data') {
    request.body = {
      ...request.body,
      _t: Date.parse(new Date()) / 1000
    }
  } else if (request.method === 'GET') {
    request.params = {
      _t: Date.parse(new Date()) / 1000,
      ...request.params
    }
  }
  return request
})

request.interceptors.response.use(function(response) { //不要使用箭头函数，否则调用this.lock()时，this指向不对 
  let errmsg = '';
  const data = response.data;
  if (!data || typeof data !== 'object') {
    errmsg = '服务器响应格式错误';
    uni.showToast({
      title: errmsg,
      icon: 'none'
    })
  } 
  return response.data; //只返回业务数据部分
}, function(err) {
  let errmsg = err.message;
  switch (err.status) {
    case 401:
	  uni.switchTab({
	  	url: '/pages/index/index'
	  })
      break;
    default:
      uni.showToast({
        title: errmsg,
        icon: 'none'
      })
  }
})

export default request
